package com.hktf.uilib.app;

import android.Manifest;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.ColorInt;
import androidx.annotation.LayoutRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import com.hktf.corelib.constant.KEYS;
import com.hktf.corelib.constant.LocationState;
import com.hktf.corelib.eventBus.BaseEvent;
import com.hktf.corelib.eventBus.DialogBean;
import com.hktf.corelib.eventBus.ObjectEvent;
import com.hktf.corelib.utils.CommUtils;
import com.hktf.corelib.utils.Config;
import com.hktf.corelib.utils.FileUtil;
import com.hktf.corelib.utils.LogMds;
import com.hktf.corelib.utils.MMKVUtils;
import com.hktf.corelib.utils.PreferenceUtil;
import com.hktf.corelib.utils.UIUtils;
import com.hktf.uilib.R;
import com.hktf.uilib.utils.DisplayUtil;
import com.hktf.uilib.utils.DlgUtils;
import com.hktf.uilib.utils.EDensityUtils;
import com.hktf.uilib.utils.PermissionHelper;
import com.hktf.uilib.utils.RootUtil;
import com.hktf.uilib.widget.RequestPermissionDialog;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.ExplainReasonCallbackWithBeforeParam;
import com.permissionx.guolindev.callback.ForwardToSettingsCallback;
import com.permissionx.guolindev.callback.RequestCallback;
import com.permissionx.guolindev.request.ExplainScope;
import com.permissionx.guolindev.request.ForwardScope;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Locale;


/**
 * @author cdz
 * @ClassName: BaseActivity
 * @Description: TODO 本工程Activity类的基类
 * @date 2025-3-2 上午9:19:28
 */
public abstract class BaseActivity extends AppCompatActivity {
    protected static final String TAG = "BaseActivity";
    private final static String LOG_TAG = BaseActivity.class.getSimpleName();
    private static final int REQUEST_MEDIA_PROJECTION = 0x200;
    private static final int ACTION_MANAGE_OVERLAY_PERMISSION = 0x201;
    public static final int ACTION_MANAGE_OVERLAY_PERMISSION_FOR_REMOTEDIA = 0x202;
    public Context context;
    public UiApplication appContext;
    // 定义window manager
    public WindowManager wm = null;
    public TextView voliage_text;
    public ImageView back = null;
    // 定义window manager
    protected ImageView backbtn = null;
    // 悬浮返回按钮是否显示
    protected boolean isBackShow = false;
    protected UiApplication application;
    private RelativeLayout rl_screenrecoder = null;
    /**
     * @Fields progressDialog : TODO 等待框
     */
    private Dialog progressDialog;

    private Dialog dialog = null;
    // wupeng add

    /**
     * 快速诊断提示框广播
     */

    public HorizontalScrollView mTitleScrollView;

    public void setFlag(){
        getWindow().addFlags(
                LayoutParams.FLAG_KEEP_SCREEN_ON |
                        LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                        LayoutParams.FLAG_TURN_SCREEN_ON|
                        LayoutParams.FLAG_DISMISS_KEYGUARD
        );
    }



    /**
     * 初始化屏幕方向
     */
    public void initScreenState() {
        try {
            if (!"YDS-B80-Android".equals(Config.CLIENTNAME) || !"YDS-B90-Android".equals(Config.CLIENTNAME) || !"YDS-B80PRO-Android".equals(Config.CLIENTNAME)
                    || !"YDS-B80-EN-Android".equals(Config.CLIENTNAME) || !"YDS-B80-YOULIBO-Android".equals(Config.CLIENTNAME)
                    || !"YDS-B80-BOGELI-Android".equals(Config.CLIENTNAME) || !"YDS-C81-Android".equals(Config.CLIENTNAME) || !"YDS-C90-AREA-Android".equals(Config.CLIENTNAME)) {
                if (Config.islandscape) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    this.getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN,
                            LayoutParams.FLAG_FULLSCREEN);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                LogMds.w("cdz", "Config.islandscape=" + Config.islandscape + "...className=" + this.getClass().getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
//        }
//        getWindow().setAttributes(lp);

//        setContentView(getLayoutResID());
        rootView=View.inflate(this,getLayoutResID(),null);
        setContentView(rootView);
        setStatusBarAndNavBar(getStatusBarColor(), getNavBarColor(), showStatusBarAndNavBar(), isStatusBarAndNavBarUiWhite());
        beforeAddtoStack();
        commonInit();
        initView();
        initListener();
        initData();
    }

    private void commonInit() {
        //从sp拿到屏幕的方向
        initScreenState();
        // 初始化PreferenceUtil
        PreferenceUtil.init(this);
        // 根据上次的语言设置，重新设置语言
        switchLanguage(PreferenceUtil.getString("language",
                Locale.SIMPLIFIED_CHINESE.getLanguage()));
        context = BaseActivity.this;
        application = (UiApplication) this.getApplication();
        application.getActivityManager().pushActivity(this);
        appContext = (UiApplication) getApplicationContext();
        getWindow().setSoftInputMode(
                LayoutParams.SOFT_INPUT_STATE_HIDDEN);


        // 判断sdcard的大小
        try {
            if (FileUtil.getSDFreeSize() < 10) {
                Toast.makeText(BaseActivity.this,
                        getResources().getString(R.string.sd_kongjian),
                        Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            EventBus.getDefault().register(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //        getWindow().getDecorView().setPadding(100,200,100,200);

        screenHeight= DisplayUtil.getMetricsHeight(this);
        screenWidth = DisplayUtil.getMetricsWidth(this);
        autoSizeType = getAutoSizeType();
        switch (autoSizeType) {
            case 0:
                break;
            case 1:
                setAutoSizeDependWidth();
                break;
            case 2:
                setAutoSizeDependHeight();
                break;
        }
    }

    public int screenHeight;
    private int screenWidth;

    /**
     * 获取布局文件id
     *
     * @return
     */
    public abstract @LayoutRes int getLayoutResID();

    /**
     * 在onCreate()方法中调用，在该方法中可以执行findviewbyid
     */
    public abstract void initView();

    /**
     * 在onCreate()方法中调用，bindviews方法执行后调用
     */
    public abstract void initListener();

    /**
     * 在onCreate()方法中调用，initListener完成之后调用的方法,可以在该方法中获取数据
     */
    public abstract void initData();

    /**
     * 在onCreate()方法中调用，在actiity被放入栈之前调用
     */
    public void beforeAddtoStack(){

    }

    /**
     * 设置状态栏和导航栏的背景颜色
     */
    public @ColorInt int getStatusBarColor() {
        return UIUtils.getColor(R.color.white);

    }

    /**
     * 设置状态栏和导航栏的背景颜色
     */
    public @ColorInt int getNavBarColor() {
        return UIUtils.getColor(R.color.white);
    }

    /**
     * 设置状态栏和导航栏是否显示
     */
    public boolean showStatusBarAndNavBar() {
        return true;
    }

    /**
     * 设置状态栏和导航栏字体是否是白色 是为白色 否则为黑色
     */
    public boolean isStatusBarAndNavBarUiWhite() {
        return false;
    }


    public void setStatusBarAndNavBar(){
        setStatusBarAndNavBar(getStatusBarColor(), getNavBarColor(), showStatusBarAndNavBar(), isStatusBarAndNavBarUiWhite());
    }

    public int statusBarHeight;
    public int navBarHeight;

    public static int getStatusBarHeight(Context context) {
        int result = 0;
        if (context instanceof BaseActivity) {
            BaseActivity baseActivity= (BaseActivity) context;
            result = baseActivity.statusBarHeight;
        }
        return result;
    }
    public static int getNavBarHeight(Context context) {
        int result = 0;
        if (context instanceof BaseActivity) {
            BaseActivity baseActivity= (BaseActivity) context;
            result = baseActivity.navBarHeight;
        }
        return result;
    }




    /**
     * 设置系统状态栏和导航栏颜色和是否显示
     *
     * @param showStatusBarAndNavBar 是否显示导航栏和状态栏
     * @param isSystemUiWhite        导航栏和状态栏图标颜色
     */
    public void setStatusBarAndNavBar(@ColorInt int statusBarColor, @ColorInt int navBarColor, boolean showStatusBarAndNavBar, boolean isSystemUiWhite) {
        Window window = getWindow();
        View decorView = window.getDecorView();
        LogMds.e("cdz", "============================isSystemUiWhite="+isSystemUiWhite);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            LogMds.e("cdz", "=================================================1");
            // Android 11及以上
            window.setDecorFitsSystemWindows(false);
            WindowInsetsController controller = window.getInsetsController();
            if (controller != null) {
                if (showStatusBarAndNavBar) {
                    //显示导航栏和状态栏
                    if (isSystemUiWhite) {
                        // 设置状态栏和导航栏图标为白色
                        controller.setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS |
                                WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);
                    } else {
                        // 设置状态栏和导航栏图标为黑色
                        controller.setSystemBarsAppearance(
                                WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS |
                                        WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,
                                WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS |
                                        WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);
                    }
                } else {
                    //不显示系统导航栏和状态栏
                    controller.hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
                    // 设置沉浸式粘性模式，用户交互后系统栏短暂显示后再次隐藏
                    controller.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
                }
            }


        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android 6.0 - Android 10
            LogMds.e("cdz", "=================================================2");
            if (showStatusBarAndNavBar) {
                int systemUiVisibility = decorView.getSystemUiVisibility();
                if (isSystemUiWhite) {
                    // 状态栏和导航栏图标和字体为白色
                    systemUiVisibility &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                    systemUiVisibility &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
                    decorView.setSystemUiVisibility(systemUiVisibility);
                } else {
                    // 状态栏和导航栏图标和字体为黑色
                    systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                    systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
                    decorView.setSystemUiVisibility(systemUiVisibility);
                }
            } else {
                // Android 4.4 到 Android 10
                int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(uiOptions);
            }

        }


        // 处理布局与状态栏重叠
        if (showStatusBarAndNavBar) {
            LogMds.e("cdz", "=================================================3isLayoutFitsSystemWindows="+isLayoutFitsSystemWindows());
            if (!isLayoutFitsSystemWindows()) {
                decorView.setOnApplyWindowInsetsListener((v, insets) -> {
                    statusBarHeight = insets.getSystemWindowInsetTop();
                    navBarHeight = insets.getSystemWindowInsetBottom();
                    // 设置状态栏和导航栏背景
//                    v.setPadding(0, statusBarHeight, 0, navBarHeight);
//                    decorView.setPadding(0, statusBarHeight, 0, navBarHeight);
                    if (rootView != null) {
                        rootView.setPadding(0, statusBarHeight, 0, navBarHeight);
                    }
                    LogMds.e("cdz", "=================================================statusBarHeight="+statusBarHeight);
                    LogMds.e("cdz", "=================================================navBarHeight="+navBarHeight);
                    return insets;
                });
            }

            // 设置状态栏和导航栏背景为黑色
            //            window.setStatusBarColor(getResources().getColor(android.R.color.black));
            //            window.setNavigationBarColor(getResources().getColor(android.R.color.black));

            window.addFlags(Integer.MIN_VALUE);
            window.setStatusBarColor(statusBarColor);
            window.setNavigationBarColor(navBarColor);
        }else {
            //设置布局延伸到刘海屏内，没此处设置会导致小米手机顶部导航栏显示黑色。重要重要
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                try {
                    LayoutParams lp = getWindow().getAttributes();
                    lp.layoutInDisplayCutoutMode = LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
                    getWindow().setAttributes(lp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


    }
    private boolean isSetyWindowInsetsListener;

    public void setRootViewPaddingTop(View view){
        LogMds.e("cdz", "===========================setRootViewPaddingTop======================statusBarHeight="+statusBarHeight);
        LogMds.e("cdz", "================================setRootViewPaddingTop=================navBarHeight="+navBarHeight);
        rootView.setPadding(0, 0, 0, navBarHeight);
        view.setPadding(0, statusBarHeight, 0, 0);
        if (!isSetyWindowInsetsListener) {
            isSetyWindowInsetsListener=true;
            rootView.getRootView().setOnApplyWindowInsetsListener((v, insets) -> {
                statusBarHeight = insets.getSystemWindowInsetTop();
                navBarHeight = insets.getSystemWindowInsetBottom();
                // 设置状态栏和导航栏背景
//                    v.setPadding(0, statusBarHeight, 0, navBarHeight);
//                    decorView.setPadding(0, statusBarHeight, 0, navBarHeight);
                if (rootView != null) {
                    rootView.setPadding(0, 0, 0, navBarHeight);
                }
                view.setPadding(0, statusBarHeight, 0, 0);
                LogMds.e("cdz", "=================================================statusBarHeight="+statusBarHeight);
                LogMds.e("cdz", "=================================================navBarHeight="+navBarHeight);
                return insets;
            });
        }
    }

    /**
     * 布局文件是否已经开启适配系统状态栏 开启后不需要设置decorView的padding
     * @return
     */
    public boolean isLayoutFitsSystemWindows(){
        return false;
    }


    public View rootView;

    public void sendScreenShot() {
        try {
            if (true) {
                return;
            }
            if (rootView == null) {
                rootView = getWindow().getDecorView().findViewById(android.R.id.content);
                return;
            }
            int height = rootView.getHeight();
            int width = rootView.getWidth();


            View decorView = getWindow().getDecorView();
            decorView.setDrawingCacheEnabled(true);
            decorView.buildDrawingCache();
            Bitmap drawingCache = decorView.getDrawingCache();
            //                Matrix matrix=new Matrix();
            //                matrix.postScale(1f,1f);
            //            Bitmap bitmap = Bitmap.createBitmap(drawingCache,0,0,width/4,height/4);
            //            Bitmap bitmap = Bitmap.createBitmap(drawingCache, 0, 0, width, height);
            Bitmap bitmap = Bitmap.createScaledBitmap(drawingCache, width / 2, height / 2, true);
            decorView.setDrawingCacheEnabled(false);
            // 获取一个输出流，用于将Bitmap转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            byte[] bitmapData = outputStream.toByteArray();
            //            rootView.destroyDrawingCache();

            LogMds.e("bitmap", "bitmap size=" + bitmapData.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ObjectEvent event) {
        //        LogMds.w("cdz", "收到消息了............isOnPause=" + isOnPause);
        if (event != null) {
            int event_id = event.getEventId();
            if (isOnPause) {
                return;
            }
            switch (event_id) {
                case ObjectEvent.BT_AUTOCONNECT_FAIL:
                    break;
                case ObjectEvent.EXIT_APP://退出应用
                    exitApp();
                    break;
                case ObjectEvent.other:
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEvent<DialogBean> event) {
        //        LogMds.w("cdz", "收到消息了............isOnPause=" + isOnPause);
        if (event != null) {
            int event_id = event.getEVENT_ID();
            if (event_id == BaseEvent.DISMISS_DIALOG) {
                LogMds.w("cdz", "收到关闭弹窗消息了............");
                DlgUtils.dissmissDialog(dialog);
                //                DlgUtils.disMissDlg();
            }
            if (isOnPause) {
                return;
            }
            if (event_id != BaseEvent.SHOW_DIALOG) {
                return;
            }
            DialogBean data = event.getData();
            if (data == null) {
                return;
            }
            int type = data.getType();
            switch (type) {
                case DialogBean.TYPE_OK:
                    break;
                case DialogBean.TYPE_WAIT:
                    break;
                case DialogBean.TYPE_WAIT_NO_CANCEL:
                    String msg = data.getMsg();
                    if (msg == null) {
                        return;
                    }
                    DlgUtils.showLoadingDlg(msg, this);
                    break;
            }
        }
    }


    public static String headCaption;


    @Override
    protected void onStart() {

        super.onStart();
    }

    protected void switchLanguage(String language) {
        // 设置应用语言类型
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        if (language.equals(Locale.ENGLISH.toString())) {
            config.locale = Locale.ENGLISH;
        } else if (language.equals(Locale.TRADITIONAL_CHINESE.toString())) {
            config.locale = Locale.TRADITIONAL_CHINESE;

        } else {
            config.locale = Locale.SIMPLIFIED_CHINESE;

        }
        resources.updateConfiguration(config, dm);

    }

    private boolean isFirst;

    @Override
    protected void onResume() {
        super.onResume();
        if (isFirst) {
            isFirst = false;
        } else {
            sendScreenShot();
        }

        isOnPause = false;


        //修改录屏功能显示紊乱，从底层菜单停止录屏后，返回上一级菜单仍显示录屏
        // rl_screenrecoder  = (RelativeLayout) findViewById(R.id.rl_screenrecoder);
        if (rl_screenrecoder != null) {
            if (Config.isScreenRecoder) {
                rl_screenrecoder.setVisibility(View.VISIBLE);
            } else {
                rl_screenrecoder.setVisibility(View.GONE);
            }
        }

    }


    public boolean isOnPause;

    @Override
    protected void onPause() {
        isOnPause = true;
        LogMds.d(LOG_TAG, "onPause");
        super.onPause();
    }


    /*
     * 显示titlebar右边的按钮
     */

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        LogMds.d(LOG_TAG, "onDestroy");
        super.onDestroy();
        if (autoSizeType != 0) {
            autoSizeReset();
        }
        try {
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        popStackActivity();
        // 移除悬浮窗口
        if (isBackShow) {
            isBackShow = false;
        }
    }


    /*
     * (non Java doc) <p>Title: onBackPressed</p> <p>Description: </p>
     *
     * @see android.app.Activity#onBackPressed()
     */
    @Override
    public void onBackPressed() {
        if(!onBack()){
            super.onBackPressed();
        }
    }

    private void popStackActivity() {
        UiApplication application = (UiApplication) this.getApplication();
        application.getActivityManager().popActivity(this);
    }


    /**
     * @return void
     * @throws
     * @Title: dismissProgress
     * @Description: TODO 取消等待框
     */
    protected void dismissProgress() {
        if (progressDialog != null) {
            try {
                progressDialog.dismiss();
            } catch (Exception e) {

            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(BaseActivity.this,
                        getResources().getString(R.string.photo_is_ok),
                        Toast.LENGTH_LONG).show();
            }
        }
        switch (requestCode) {
            case REQUEST_MEDIA_PROJECTION:
                //屏幕录制
                break;
            case ACTION_MANAGE_OVERLAY_PERMISSION:
                //截屏请求悬浮窗权限
                LogMds.e("screenrecorder", "resultCode=" + resultCode);
                break;
        }
    }




    public void addFloatWindow() {
        if (wm != null && isBackShow) {
            // 显示myFloatView图像
            // wm.addView(backbtn, wmParams);
            backbtn.setVisibility(View.VISIBLE);
        }
    }

    public void removeFloatWindow() {
        if (isBackShow) {
            backbtn.setVisibility(View.INVISIBLE);
        }
    }


    public void onNeedUpadate() {
        // TODO: 2022/4/24 资源有更新需要升级
        Config.NEED_UPGRADE = true;
    }


    public void checkSDFreeSize() {
        try {
            long sdFreeSize = FileUtil.getSDFreeSize();
            LogMds.i("cdz", "可用空间：" + sdFreeSize + "MB");
            if (sdFreeSize < 200) {
                //                DlgUtils.showInformationDlg(this, getString(R.string.free_size_not_enough));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 退出应用
     */
    public void exitApp() {
        // TODO Auto-generated method stub

        UiApplication.getInstance().getActivityManager().popAllActivities();
        System.exit(0);
    }


    /**
     * 蓝牙连接状态变化回调
     *
     * @param status
     */
    public void onConnectStatusChange(int status) {

    }


    public class RemoteServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

    }


    public void checkRoot() {
        boolean deviceRooted = RootUtil.isDeviceRooted();
        LogMds.e("deviceRooted", "deviceRooted=" + deviceRooted);
        if (deviceRooted) {
            exitApp();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //        if (Config.isRemotingFlash) {
        //            MotionEventBean bean=new MotionEventBean();
        //            bean.setAction(ev.getAction());
        //            bean.setX(ev.getX());
        //            bean.setY(ev.getY());
        ////            object.addProperty("action",ev.getAction());
        //            RemoteDiaEvent.Companion.sendMsg(RemoteConstant.CONTROL_MOVENTION_EVENT, GsonUtils.createGsonString(bean));
        //
        //        }

        //        LogMds.w("MotionEvent", "MotionEvent=" + ev);
        //        LogMds.e("cdzRemote","dispatchTouchEvent  x="+ev.getX()+"..y="+ev.getY());
        if (Config.isRemotingFlash) {
            return true;
        }

        return super.dispatchTouchEvent(ev);
    }

    public void setAutoSizeDependWidth() {
        EDensityUtils.setDependWidth(360f);
        EDensityUtils.setDensityDependOnWidth(getApplication(), this);
    }

    public void setAutoSizeDependHeight() {
        EDensityUtils.setDependHeight(733f);
        EDensityUtils.setDensityDependOnHeight(getApplication(), this);
    }

    public void autoSizeReset() {
        EDensityUtils.reset(this);
    }

    public void setTitle(String title) {
        TextView title_text = findViewById(R.id.title_text);
        title_text.setText(title);
    }

    public void setBackClick() {
                findViewById(R.id.titlebar_back).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
    }

    public Object object;


    public void getLocation() {
        PermissionX.init((FragmentActivity) context)
                .permissions(
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                )
                .explainReasonBeforeRequest()
                .onExplainRequestReason(new ExplainReasonCallbackWithBeforeParam() {
                    @Override
                    public void onExplainReason(ExplainScope scope, List<String> deniedList, boolean beforeRequest) {
                        for (String str : deniedList) {
                            LogMds.d("hxwPer", "str " + str);
                        }
                        //                        scope.showRequestReasonDialog(deniedList, "车主版需要您同意以下权限才能正常使用", "同意");
                        scope.showRequestReasonDialog(new RequestPermissionDialog(context, "缺少位置权限", "开启后可获取定位信息\n用于展示您所在维修站或当前位置信息", deniedList));
                        //                        onLocationResult(null, null, LocationState.ERROR0);
                    }
                })
                .onForwardToSettings(new ForwardToSettingsCallback() {
                    @Override
                    public void onForwardToSettings(ForwardScope scope, List<String> deniedList) {
                        for (String str : deniedList) {
                            LogMds.d("hxwPer", "str " + str);
                        }
                        //                        scope.showForwardToSettingsDialog(deniedList, "您需要去设置中手动开启以下权限", "确定");
                        scope.showForwardToSettingsDialog(new RequestPermissionDialog(context, "缺少位置权限", "您需要去设置中手动开启定位权限\n开启后可获取定位信息\n用于展示您所在维修站或当前位置信息", deniedList));
                        //                        onLocationResult(null, null, LocationState.ERROR1);
                    }
                })
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                        if (allGranted) {

                        } else {
                            Toast.makeText(context, "您拒绝了定位权限", Toast.LENGTH_SHORT).show();
                            onLocationResult(null, null, LocationState.ERROR0);
                        }
                    }
                });
    }

    public void onLocationResult(String lon, String latitude, LocationState state) {

    }


    public void showLoadingSend() {
        DlgUtils.showLoadingSend(this);
    }
    public void showLoadingGet() {
        DlgUtils.showLoadingGet(this);
    }

    public void showLoadingDlg(String msg) {
        DlgUtils.showLoading(this, msg, false, null);
    }

    public void showInfoDlg(String msg,DlgUtils.MyListener listener){
        DlgUtils.showDlgNew(this,null,msg,
                UIUtils.getString(R.string.ok),
                null,true,listener);
    }
    public void gotoCall(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return;
        }
        PermissionX.init(this)
                .permissions(Manifest.permission.CALL_PHONE)
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                        if (allGranted) {
                            //Toast.makeText(SplashActivity.this, "所有申请的权限都已通过", Toast.LENGTH_SHORT).show();
                            try {
                                Intent intent = new Intent();
                                intent.setAction("android.intent.action.CALL");
                                intent.setData(Uri.parse("tel:" + phone));
                                startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            //                                Toast.makeText(getActivity(), UIUtils.getString(com.hktf.uilib.R.string.permission_denied), Toast.LENGTH_SHORT).show();
                            //跳转应用消息，间接打开应用权限设置-效率高
                            PermissionHelper.gotoSetting(BaseActivity.this, getString(R.string.call_phone_unenable));
                        }
                    }
                });
    }

    private int autoSizeType;//0没有自动适配 1依据屏幕宽度适配 2依据屏幕高度适配

    public int getAutoSizeType() {
        return 0;
    }


    public boolean onBack() {
        return false;
    }

    /**
     * 隐藏顶部诊断记录导航栏
     */
    public void hideHistoryCaption() {
        View parent = (View) mTitleScrollView.getParent();
        parent.setVisibility(View.GONE);
    }

    // 字体大小不跟随系统
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(getConfigurationContext(newBase));
    }

    private static Context getConfigurationContext(Context context) {
        Configuration configuration = context.getResources().getConfiguration();
        configuration.fontScale = 1;
        return context.createConfigurationContext(configuration);
    }



    public void saveCheckLock(int resId){
        MMKVUtils.putInteger(KEYS.LOCK_RESID,resId);
    }

    public void checkFloatPermission(){
        if (PermissionHelper.checkFloatPermission(this)) {

        } else {
            if (Build.VERSION.SDK_INT >= 23) {//6.0以上
                DlgUtils.requestPermission(this, "缺少缺少悬浮窗权限", "开启后可显示于其他应用之上，\n" +
                        "用于截屏和远程诊断功能", new DlgUtils.MyListener() {
                    @Override
                    public void onConfirm() {
                        try {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
            } else {
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                intent.setData(Uri.fromParts("package", getPackageName(), null));
            }
        }
    }


}
